package com.alibaba.cloud.ai.example.flight.service;

import com.alibaba.cloud.ai.example.flight.model.Flight;
import com.alibaba.cloud.ai.example.flight.model.FlightData;
import com.alibaba.cloud.ai.example.flight.model.command.FlightCommand;
import com.alibaba.cloud.ai.example.flight.model.query.FlightQuery;
import jakarta.annotation.Resource;
import org.apache.commons.codec.binary.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Service
public class FlightService {

    @Resource
    private FlightData flightData;

    /**
     * 查询全部的航班列表
     */
    public List<Flight> queryFilghtList() {
        return flightData.getFlightList();
    }

    /**
     * 查询指定人员的航班信息
     * - 单独的对象字段
     */
    public Flight queryFlight(String name, Integer orderId) {
        return queryFilghtList().stream().filter(item -> StringUtils.equals(name, item.getName()) && orderId.equals(item.getId())).findFirst().orElse(null);
    }

    /**
     * 查询指定人员的航班信息
     * - 对象传参
     */
    public Flight queryFlight(FlightQuery flightQuery) {
        return queryFilghtList().stream().filter(item -> StringUtils.equals(flightQuery.getName(), item.getName()) && flightQuery.getOrderId().equals(item.getId())).findFirst().orElse(null);
    }


    /**
     * 添加一个新的航班信息
     */
    public void addFlight(FlightCommand flightCommand) {
        Flight newFlight = flightCommand.convert2Flight();
        List<Flight> flights = queryFilghtList();
        Integer maxOrderId = flights.stream().max(Comparator.comparingInt(Flight::getId)).orElseThrow().getId();
        newFlight.setId(maxOrderId + 1);
        flights.add(newFlight);
        flightData.setFlightList(flights);
    }

}
